package ar.edu.unq.tpi.uis.tepe3.wicket.components;

import java.util.ArrayList;
import java.util.List;

import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.form.DropDownChoice;
import org.apache.wicket.model.PropertyModel;
import org.hibernate.Session;
import org.hibernate.Transaction;

import ar.edu.unq.tpi.uis.tepe3.dominio.Group;
import ar.edu.unq.tpi.uis.tepe3.dominio.User;
import ar.edu.unq.tpi.uis.tepe3.persistencia.HibernateUtil;
import ar.edu.unq.tpi.uis.tepe3.wicket.pages.UserPage;

@SuppressWarnings("serial")
public abstract class AbstractUserToGroupForm<T, E> extends AbstractFormABM<T>{

	private E selected;
	
	public AbstractUserToGroupForm(String id, T object) {
		super(id, object);
	}

	@Override
	protected void addFields() {
		this.add(new Label("name"));
		this.add(new DropDownChoice("selectable", new PropertyModel(this, "selected"), this.getAllSelectables()));
	}

	protected List<E> getAllSelectables() {
		List<E> list = new ArrayList<E>();
		Session sess = HibernateUtil.getSessionFactory().getCurrentSession();
		Transaction tx = null;
		try {
			tx = sess.beginTransaction();
//			list = sess.createCriteria(this.selected.getClass()).list();
			list = sess.createCriteria(this.getSelectableClass()).list();
			tx.commit();
		} catch (RuntimeException e) {
			if (tx != null)
				tx.rollback();
			throw e;
		} finally{
			if(sess.isOpen()) sess.close();
		}
		return list;
	}
	
	protected abstract Class<E> getSelectableClass();
	
	@Override
	protected void updateObject(Session sess) {
		super.updateObject(sess);
		sess.refresh(this.getObject());
		this.asignar(this.selected);
//		if(this.getSelectableClass() == Group.class){
//			((User) this.getObject()).addGroup((Group) this.getSelected());
//			System.out.println(((User) this.getObject()).getGroups());
//		}else{
//			((Group) this.getObject()).addUser((User) this.getSelected());
//			System.out.println(((Group) this.getObject()).getUsers());
//		}
	}
	
	protected abstract void asignar(E selected);

	public E getSelected() {
		return selected;
	}

	public void setSelected(E selected) {
		this.selected = selected;
	}

}
